package cn.qicaiwang.open.admin.controller.common;

import cn.hutool.core.util.StrUtil;
import cn.qicaiwang.open.common.constant.CacheConstants;
import cn.qicaiwang.open.common.constant.Constants;
import cn.qicaiwang.open.common.enums.ResultStatusCodeEnum;
import cn.qicaiwang.open.common.enums.SmsCodeEnum;
import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.common.utils.AesUtil;
import cn.qicaiwang.open.common.utils.ImageCodeUtil;
import cn.qicaiwang.open.common.utils.sms.TencentSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 */
@Slf4j
@RestController
@RequestMapping(value = "captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private Executor threadPoolTaskExecutor;

    @GetMapping("image")
    public void image(String key, HttpServletResponse response) throws IOException {
        /*禁止缓存*/
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        /*获取验证码*/
        String code = ImageCodeUtil.generateVerifyCode(4);
        redisTemplate.opsForValue().set(CacheConstants.IMAGE_CAPTCHA_PREFIX + key, code, 5, TimeUnit.MINUTES);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageCodeUtil.outputImage(110, 40, outputStream, code);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 注册或登录验证码
     * @return
     */
    @RequestMapping("sendRegisterOrLoginCaptcha")
    public ResponseResult sendRegisterOrLoginCaptcha(String mobile){
        if(StrUtil.isBlank(mobile)){
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }
        try {
           // String inputMobile = AesUtil.decrypt(mobile);
            String captcha = RandomStringUtils.randomNumeric(6);
            redisTemplate.opsForValue().set(SmsCodeEnum.REGISTERORLOGIN.getKey() + mobile, captcha, 10, TimeUnit.MINUTES);
            String finalMobile = Constants.CN_COUNTRY_CODE + mobile;
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    TencentSmsUtils.send(SmsCodeEnum.REGISTERORLOGIN.getTemplateCode(), finalMobile, captcha);
                }
            });
            log.info("短信验证码:{}, type:{}, mobile:{}", captcha, SmsCodeEnum.REGISTERORLOGIN, mobile);
        } catch (Exception e) {
            log.error("发送短信失败:", e);
            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
        }
        return ResponseResult.ok();
    }

    /**
     * 注册或登录验证码
     * @return
     */
    @RequestMapping("sendProtocolSignatureCaptcha")
    public ResponseResult sendProtocolSignatureCaptcha(String mobile){
        if(StrUtil.isBlank(mobile)){
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }
        try {
            String inputMobile = AesUtil.decrypt(mobile);
            String captcha = RandomStringUtils.randomNumeric(6);
            redisTemplate.opsForValue().set(SmsCodeEnum.PROTOCOL_VERIFY.getKey() + mobile, captcha, 10, TimeUnit.MINUTES);
            String finalMobile = Constants.CN_COUNTRY_CODE + inputMobile;
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    TencentSmsUtils.send(SmsCodeEnum.PROTOCOL_VERIFY.getTemplateCode(), finalMobile, captcha);
                }
            });
            log.info("短信验证码:{}, type:{}, mobile:{}", captcha, SmsCodeEnum.PROTOCOL_VERIFY, inputMobile);
        } catch (Exception e) {
            log.error("发送短信失败:", e);
            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
        }
        return ResponseResult.ok();
    }

    /**
     * 注册或登录验证码
     * @return
     */
    @RequestMapping("sendFindPasswordCaptcha")
    public ResponseResult sendFindPasswordCaptcha(String mobile){
        if(StrUtil.isBlank(mobile)){
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }
        try {
            String inputMobile = AesUtil.decrypt(mobile);
            String captcha = RandomStringUtils.randomNumeric(6);
            redisTemplate.opsForValue().set(SmsCodeEnum.FIND_PASSWORD.getKey() + mobile, captcha, 10, TimeUnit.MINUTES);
            String finalMobile = Constants.CN_COUNTRY_CODE + inputMobile;
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    TencentSmsUtils.send(SmsCodeEnum.FIND_PASSWORD.getTemplateCode(), finalMobile, captcha);
                }
            });
            log.info("短信验证码:{}, type:{}, mobile:{}", captcha, SmsCodeEnum.FIND_PASSWORD, inputMobile);
        } catch (Exception e) {
            log.error("发送短信失败:", e);
            return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
        }
        return ResponseResult.ok();
    }
}
